package com.bruce.algorithm.sort;

import java.util.Arrays;

/**
 * 快速排序
 * <br>CreateDate  2021/11/03 19:08:38
 *
 * @author luotuan
 * @version 1.0.0
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] array = {1, 3, 2, 6, 8, 10, 20, 11, 9};
        sort(array, 0, array.length - 1);
        System.out.println(Arrays.toString(array));
    }

    public static void sort(int[] a, int low, int high) {
        if (low == high) {
            return;
        }
        if (low < high) {
            int position = partition(a, low, high);
            sort(a, low, position - 1);
            sort(a, position + 1, high);
        }
    }
    //找出分区点
    private static int partition(int[] a, int low, int high) {
        int center = a[high];
        int pointer = low;
        for (int i = low; i < high; i++) {
            if (a[i] <= center) {
                int tmp = a[i];
                a[i] = a[pointer];
                a[pointer] = tmp;
                pointer++;
            }
        }
        //将中心元素和指针交换
        int tmp = a[high];
        a[high] = a[pointer];
        a[pointer] = tmp;
        return pointer;
    }
}
